const purchasesModule = {
    init() {
        this.loadPurchases();
    },

    loadPurchases() {
        fetch(`${API_BASE_URL}/purchases`)
            .then(response => response.json())
            .then(purchases => {
                const html = `
                    <div class="d-flex justify-content-between align-items-center">
                        <h2>采购管理</h2>
                        <button type="button" class="btn btn-primary" id="addPurchaseBtn">新增采购</button>
                    </div>
                    <div class="table-container">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>图书名称</th>
                                    <th>采购数量</th>
                                    <th>采购单价</th>
                                    <th>采购总价</th>
                                    <th>采购时间</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${purchases.map(purchase => `
                                    <tr>
                                        <td>${purchase.book?.title || '未知'}</td>
                                        <td>${purchase.quantity}</td>
                                        <td>￥${purchase.price}</td>
                                        <td>￥${(purchase.quantity * purchase.price).toFixed(2)}</td>
                                        <td>${new Date(purchase.purchaseDate).toLocaleString()}</td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                `;
                $('#main-content').html(html);

                // 绑定事件
                $('#addPurchaseBtn').on('click', () => this.showAddPurchaseForm());
            })
            .catch(handleError);
    },

    showAddPurchaseForm() {
        // 获取图书列表
        fetch(`${API_BASE_URL}/books`)
            .then(res => res.json())
            .then(books => {
                const html = `
                    <div class="form-container">
                        <h3>新增采购</h3>
                        <form id="addPurchaseForm" class="needs-validation" novalidate>
                            <div class="mb-3">
                                <label class="form-label">选择图书</label>
                                <select class="form-select" name="bookId" required>
                                    <option value="">请选择图书</option>
                                    ${books.map(book => `
                                        <option value="${book.id}">${book.title}</option>
                                    `).join('')}
                                </select>
                                <div class="invalid-feedback">请选择图书</div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">采购数量</label>
                                <input type="number" class="form-control" name="quantity" min="1" required>
                                <div class="invalid-feedback">请输入有效的采购数量</div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">采购单价</label>
                                <input type="number" class="form-control" name="price" step="0.01" min="0" required>
                                <div class="invalid-feedback">请输入有效的采购单价</div>
                            </div>
                            <div class="d-flex gap-2">
                                <button type="submit" class="btn btn-primary">提交</button>
                                <button type="button" class="btn btn-secondary" onclick="purchasesModule.loadPurchases()">返回</button>
                            </div>
                        </form>
                    </div>
                `;
                $('#main-content').html(html);

                // 表单验证和提交
                const form = document.getElementById('addPurchaseForm');
                form.addEventListener('submit', (e) => {
                    e.preventDefault();
                    if (!form.checkValidity()) {
                        e.stopPropagation();
                        form.classList.add('was-validated');
                        return;
                    }

                    const formData = new FormData(e.target);
                    const purchase = Object.fromEntries(formData.entries());
                    // 转换数字类型
                    purchase.quantity = parseInt(purchase.quantity);
                    purchase.price = parseFloat(purchase.price);
                    
                    fetch(`${API_BASE_URL}/purchases`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(purchase)
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('采购失败');
                        }
                        return response.json();
                    })
                    .then(() => {
                        alert('采购成功！');
                        this.loadPurchases();
                    })
                    .catch(handleError);
                });
            })
            .catch(handleError);
    }
}; 